package com.chcit.mobile.mvp.receive.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.textfield.TextInputEditText;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerReceiveComponent;
import com.chcit.mobile.di.module.ReceiveModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.entity.PageBean;
import com.chcit.mobile.mvp.receive.Entity.AsnResultBean;
import com.chcit.mobile.mvp.receive.adpter.AsnAdapter;
import com.chcit.mobile.mvp.receive.api.QueryListInput;
import com.chcit.mobile.mvp.receive.contract.ReceiveContract;
import com.chcit.mobile.mvp.receive.presenter.ReceivePresenter;
import com.jess.arms.di.component.AppComponent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ReceiveBindSearchFragment extends ScanFragment<ReceivePresenter> implements ReceiveContract.View {

    @BindView(R.id.et_receive_list_package_document_no)
    SuperInputEditText etReceiveListPackageDocumentNo;
    @BindView(R.id.bt_receive_list_query)
    Button btQuery;
    @BindView(R.id.ckb_select_all)
    CheckBox selectAll;
    @BindView(R.id.bt_batch_confirm)
    Button btBatchConfirm;
    @BindView(R.id.linear_layout_show)
    LinearLayoutCompat mLinearLayout;
    @BindView(R.id.pr_receive_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_show_select)
    TextView tvShowSelect;

    AsnAdapter mAdapter ;
    List<AsnResultBean> asnResultBeanList = new ArrayList<>();
    protected MenuTypeEnum type; //入库类型  采购-PO
    private ArrayList<BpartnerBean> bpartners;
    private TextInputEditText tietProductName;
    private BpartnerBean bpartnerBean;
    private String headers[] ;
    private AsnResultBean receiveBean;
    private static int REQUEST_CODE = -4;
    private SuperTextView tvDateFrom;
    private SuperTextView tvDateTo;
    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        etReceiveListPackageDocumentNo.setText(barcodeData);
        btQuery.performClick();
    }

    @Override
    public <E> void updateContentList(List<E> receiveBeans) {
        mAdapter.addData((List<AsnResultBean>) receiveBeans);
        if(receiveBeans.size()==1){
            mAdapter.setCheckedPosition(0);
            toDeal(0);
        }

        // mAdapter.notifyDataSetChanged();
       // mLinearLayout.setVisibility(View.VISIBLE);
    }


    @Override
    public <T extends View> T getViewByTag(int i) {
        switch (i) {
            case 1:
                return (T) btQuery;
            case 2:
                break;

        }
        return null;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerReceiveComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .receiveModule(new ReceiveModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_receive, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // mAdapter.setType(type);
        mLinearLayout.setVisibility(View.GONE);
        initRecyclerView();
        initDropDownMenu();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showMessage(@NonNull String message) {

    }
    /**
     * 当有数据返回时，回调
     *
     * @param requestCode 返回状态码
     * @param resultCode  是否成功状态码
     * @param data        返回数据
     */
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE ) {
            if(requestCode == -3){
                if(mAdapter.getData().size()>mAdapter.getChekedPosition()){
                    mAdapter.remove(mAdapter.getChekedPosition());
                }
            }
        }

    }


    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();
        headers = new String[]{"选择供应商", "选择日期"};
        //供应商选择
        final ListView wareView = new ListView(getContext());
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean(1,"不限"));
        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(getContext(), bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });
        popupViews.add(wareView);
        final View dateView = getLayoutInflater().inflate(R.layout.pop_date, null);
        tvDateTo = dateView.findViewById(R.id.pop_date_drive);
        tvDateFrom = dateView.findViewById(R.id.pop_date_from);
        TextView ok = dateView.findViewById(R.id.ok);
        tvDateFrom.setCenterString(TimeDialogUtil.getBeforeDay(1));
        tvDateFrom.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateFrom.setCenterString(s), 0));
        tvDateTo.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateTo.setCenterString(s), 0));
        tvDateFrom.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3,
                        s->{
                            tvDateFrom.setCenterString(s);
                            ok.performClick();
                        },
                        0,calendar);
            }
        });
        tvDateTo.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->{
                    tvDateTo.setCenterString(s);
                    ok.performClick();
                }, 0,calendar);


            }
        });

        ok.setOnClickListener(v -> {
            StringBuffer text = new StringBuffer();
            if(!tvDateFrom.getCenterString().isEmpty()){
                text.append("开始日期：");
                text.append(tvDateFrom.getCenterString()) ;
            }
            if(!tvDateTo.getCenterString().isEmpty()){
                text .append("\n结束日期："+ tvDateTo.getCenterString());
            }

            mDropDownMenu.setTabText(text==null? headers[1] : text.toString());
            mDropDownMenu.closeMenu();
        });
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        headers[1] = "开始日期：" + TimeDialogUtil.getBeforeDay(1);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);
        tvDateTo.setRightImageViewClickListener(l -> {
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l -> {
            tvDateFrom.setCenterString("");
        });



        mPresenter.getBpartners(String.valueOf(HttpClientHelper.getSelectWareHouse().getId()), bpartnerBeans -> {
            bpartners.addAll(bpartnerBeans);
            bpartnerAdapter.notifyDataSetChanged();
        });

    }

    @OnClick({R.id.bt_receive_list_query, R.id.bt_batch_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_receive_list_query:
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                PageBean.Builder pageBuilder = new PageBean.Builder();
                pageBuilder.limit(800000)
                        .start(0);
                QueryListInput.Builder queryListInput =new  QueryListInput.Builder()
                            .page("check")
                            .asnType("PO");
                String asnNo = etReceiveListPackageDocumentNo.getText().toString();
                if (!asnNo.isEmpty()) {
                    queryListInput.asnNo(asnNo);
                }
                if (!tvDateFrom.getCenterString().isEmpty()) {
                    queryListInput.dateArrivedFrom(tvDateFrom.getCenterString());

                }
                if(!tvDateTo.getCenterString().isEmpty()){
                    queryListInput.dateArrivedTo(tvDateTo.getCenterString());
                }
                if (bpartnerBean != null && bpartnerBean.getId()!= 0) {
                   queryListInput.bpartnerId((long)bpartnerBean.getId());
                }
                queryListInput.warehouseId(HttpClientHelper.getSelectWareHouse().getId());
                mPresenter.getListData(pageBuilder.build(),queryListInput.build());
                break;
          /*  case R.id.bt_receive_date_to:
                Calendar calendarTo = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_to,calendarTo);
                break;
            case R.id.bt_receive_date_from:
                Calendar calendarFrom = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_from,calendarFrom);
                break;*/
            case R.id.bt_batch_confirm:

                break;
        }
    }

    @Override
    protected void initToolBar() {
        super.initToolBar();
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            pop();
            l.setOnClickListener(null);
            if (getActivity() != null) {
                _mActivity.finish();
            }

        });
    }


    private void initRecyclerView() {
        mAdapter= new AsnAdapter(asnResultBeanList);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter.setOnItemClickListener((adapter, view, position) -> {

            if(position>=0&& adapter.getData().size()>position){
                mAdapter.setCheckedPosition(position);
                toDeal(position);
            }
//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
        });
        mRecyclerView.setAdapter(mAdapter);

    }

    private void toDeal(int position) {
        if(position>-1&&mAdapter.getData().size()>position) {
            receiveBean = mAdapter.getData().get(position);
            startForResult(ReceiveBindSearchDetailFragment.newInstance(receiveBean,type), REQUEST_CODE);
        }
    }


}
